<!-- 客户管理-客户列表 -->
<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    <template #buts>
      <a-button type="primary" @click="add">
        <template #icon>
          <icon-plus />
        </template>
        <template #default>新增客户</template>
      </a-button>
    </template>
  </pageHeader>
  <a-space class="search-box">
    <div>
      <a-space>
        <a-input-search
          search-button
          :style="{ width: '320px' }"
          placeholder="请输入想要搜索的内容"
          @search="search"
          v-model="searchVal"
        />
        <a-button type="outline" @click="resetting">
          <template #icon> <icon-refresh /> </template>重置</a-button
        ></a-space
      >
    </div>

    <div style="margin-left: 30px">
      <a-space>
        <a-button status="success">
          <template #icon>
            <icon-download />
          </template>
          <template #default>导入</template>
        </a-button>

        <a-button status="warning" @click="getDemandDeriveData">
          <template #icon>
            <icon-export rotate="-90" />
          </template>
          <template #default>导出</template>
        </a-button>
        <a-button type="primary" @click="showFormHeaderSetting"
          >表头设置</a-button
        >
      </a-space>
    </div>
  </a-space>
  <div style="padding: 0px 10px">
    <tableTurn :tableData="getClientListData" :args="args" ref="tableTurnRef">
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        :title="item.name"
        v-for="(item, index) in selectedHeader"
        :key="index"
        :data-index="item.code"
        :width="200"
        align="center"
      >
        <!-- 创建时间item -->
        <template v-if="item.code === 'createdAt'" #cell="{ record }">
          {{ dayjs(record.createdAt).format('YYYY-MM-DD') }}
        </template>
        <!-- <template v-else-if="item.code === 'contactName'" #cell="{ record }">
            <div
              >{{
                record.person.filter((ele: any) => ele.primaryContact === 1)
                  ? record.person.filter(
                      (ele: any) => ele.primaryContact === 1
                    )[0]?.name
                  : record.person[0].name
              }}
            </div>
          </template> -->
        <!-- <template v-else-if="item.code === 'contactName'" #cell="{ record }">
            <div>{{ record.person }} </div>
          </template> -->
      </a-table-column>

      <a-table-column :width="250" align="center" title="销售负责人">
        <template #cell="{ record }">
          <div
            ><a-space :size="50"
              ><div>
                {{ record.salesName }}
              </div>
              <a-button type="primary" @click="goDetail(record.id)"
                >分配</a-button
              ></a-space
            >
          </div>
        </template>
      </a-table-column>

      <!-- 操作item -->
      <a-table-column align="center" :width="150" fixed="right" title="操作">
        <template #cell="{ record, rowIndex }">
          <div v-if="record.isNeedPerfect !== 1">
            <a-space>
              <a-tooltip content="客户档案">
                <IconFont
                  type="icon-details-def"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer',
                  }"
                  @click="goDetail(record.id)"
                />
              </a-tooltip>
              <a-tooltip content="删除">
                <a-popconfirm
                  @ok="deleteItem(record.id)"
                  content="确定删除吗"
                  type="error"
                >
                  <IconFont
                    type="icon-delete"
                    :size="26"
                    :style="{
                      marginRight: '10px',
                      cursor: 'pointer',
                    }"
                  />
                </a-popconfirm>
              </a-tooltip>
              <a-tooltip content="更多功能">
                <a-dropdown>
                  <IconFont
                    type="icon-more-def"
                    :size="26"
                    :style="{
                      marginRight: '10px',
                      cursor: 'pointer',
                    }"
                  />
                  <template #content>
                    <a-doption>
                      <a-button
                        type="text"
                        @click="changeLevel(record, rowIndex)"
                        >级别调整</a-button
                      ></a-doption
                    >
                    <!-- <a-doption disabled
                    ><a-button type="text">锁定</a-button></a-doption
                  > -->
                    <a-doption :value="{ value: 'Option3' }"
                      ><a-button
                        type="text"
                        @click="changeBlack(record.id, rowIndex)"
                        >转黑名单</a-button
                      ></a-doption
                    >
                  </template>
                </a-dropdown>
              </a-tooltip>
            </a-space>
          </div>
          <div v-else>
            <a-space>
              <a-button type="primary" status="success" @click="edit(record.id)"
                >完善信息</a-button
              >
              <a-button type="text" @click="goDetail(record.id)">详情</a-button>
              <a-popconfirm
                @ok="deleteItem(record.id, rowIndex)"
                content="确定删除吗"
                type="error"
              >
                <a-button
                  type="text"
                  :style="{
                    color: 'red',
                  }"
                  >删除</a-button
                >
              </a-popconfirm>
            </a-space>
          </div>
        </template>
      </a-table-column>
    </tableTurn>
  </div>
  <FormHeaderSetting
    v-model:visible="formHeaderSettingVisible"
    title="客户列表表头设置"
    :resultList="headerSetting.list"
    @headerSave="headerSave"
    :forbidList="forbidList"
  ></FormHeaderSetting>

  <reassignModal> </reassignModal>
  <levelModal
    v-if="levelModalVisible"
    :pre-level="currLevel"
    @changeLevelEmit="changeLevelEmit"
    v-model:visible="levelModalVisible"
  ></levelModal>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, watchEffect, watch } from 'vue';
  import { useRouter } from 'vue-router';
  import { pageData as IpageData } from '@/types/global';
  import {
    GetClientHeader,
    PutClientHeader,
    GetClientList,
    PutClientState,
    DelClientList,
    PutClient2Black,
    GetClientDeriveExcel,
  } from '@/api/order-management/client-management/client-list';
  import cloneDeep from 'lodash.clonedeep';
  import dayjs from 'dayjs';
  import { formHeaderSetting } from '@/types/global';
  import levelModal from './components/change-level-modal/index.vue';
  import reassignModal from './components/reassign-modal/index.vue';

  const router = useRouter();
  const title = '客户列表';
  const breadCrumb = ['订单管理', '客户管理', '客户列表'];

  const headerSetting = reactive<any>({
    list: [],
  });

  const forbidList = reactive(['salesName']); // 禁止移动的表头， (销售员)

  // 表格配置
  const args = reactive({
    stripe: true,

    scroll: {
      y: 500,
    },
    bordered: {
      headerCell: true,
    },
    rowKey: 'name', // 批量选择按钮以客户名称来作为key
  });
  let searchVal = ref(''); // 储存搜索框值
  let tableTurnRef: any = ref(); // 储存table的ref
  let isFirstSelect = ref(true);
  // 获取客户列表数据
  const getClientListData = async (pageData?: any) => {
    isFirstSelect.value = false;
    try {
      const res = await GetClientList({
        ...pageData,
        keyWord: searchVal.value,
      });
      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  // 搜索框
  const search = async () => {
    tableTurnRef.value.refreshPaging();
    tableTurnRef.value.loadData();
  };

  const columns = [
    {
      name: '客户编号',
      code: 'customerNumber',
      isDefault: 1,
    },
    {
      name: '客户名称',
      code: 'name',
      isDefault: 1,
    },
    {
      name: '客户级别',
      code: 'levelName',
      isDefault: 1,
    },
    {
      name: '联系电话',
      code: 'customerContactPhone',
      isDefault: 1,
    },
    {
      name: '联系邮箱',
      code: 'customerEmail',
      isDefault: 1,
    },
    {
      name: '省市区',
      code: 'city',
      isDefault: 1,
    },
    {
      name: '详细地址',
      code: 'address',
      isDefault: 1,
    },
    {
      name: '客户来源',
      code: 'sourceName',
      isDefault: 1,
    },
    {
      name: '客户行业',
      code: 'industry',
      isDefault: 1,
    },
    {
      name: '客户类别',
      code: 'customerTypeName',
      isDefault: 1,
    },
    {
      name: '联系人',
      code: 'person[0].name',
      isDefault: 1,
    },
    {
      name: '联系人职位',
      code: 'person[0].job',
      isDefault: 1,
    },
    {
      name: '联系人部门',
      code: 'person[0].department',
      isDefault: 1,
    },
    {
      name: '联系人手机',
      code: 'person[0].phone',
      isDefault: 1,
    },
  ];

  // watchEffect(() => {
  //   if (!isFirstSelect.value && searchVal.value === '')
  //     tableTurnRef.value.loadData();
  // });

  // 获取表头设置列表
  const HeadersId = ref();
  const getHeaders = async () => {
    try {
      const res = await GetClientHeader({ listType: 1 });
      if (res.id === 0) {
        headerSetting.list = columns;
      } else {
        headerSetting.list = res.extends;
      }
      // headerSetting.list = res.extend;
      // HeadersId.value = res.id;
    } catch (error: unknown) {
      console.log(error);
    }
  };
  getHeaders();

  // 在表格上显示的表头
  const selectedHeader = computed(() => {
    const arr: formHeaderSetting['list'] = [];
    headerSetting.list.forEach((item) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });
  // 储存客户人员信息
  const clientList = reactive([]);

  // 点击新增人员
  const add = (): void => {
    router.push({
      name: 'ClientInfoAdd',
      query: {
        type: 'add',
      },
    });
  };

  // 点击完善信息
  const edit = (id): void => {
    router.push({
      name: 'ClientInfoAdd',
      query: {
        type: 'add',
        id,
      },
    });
  };

  let formHeaderSettingVisible = ref<boolean>(false); // 是否显示表头设置组件

  // 表头设置按钮
  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };

  // 表头设置保存后返回的自定义事件
  const headerSave = async (headerList: formHeaderSetting['list']) => {
    try {
      const data = {
        listType: 1,
        extend: JSON.stringify(headerList),
      };
      await PutClientHeader(data);
      headerSetting.list = [...headerList];
    } catch (err: unknown) {
      console.log(err);
    }
  };

  let currId = ref(-1); // 储存当前选中的id

  // 去往对应的详情页面
  const goDetail = (id: number) => {
    router.push({
      name: 'ClientInfoDetail',
      query: {
        id,
      },
    });
  };

  let levelModalVisible = ref(false); // 判断是否点击级别调整按钮
  let currLevel = ref('');
  // 修改级别
  const changeLevel = (record: any, index: number) => {
    currId.value = record.id;
    currLevel.value = record.levelName;
    levelModalVisible.value = true;
  };

  const resetting = () => {
    searchVal.value = '';
    tableTurnRef.value.refreshPaging();
    tableTurnRef.value.loadData();
  };

  // 修改级别按钮返回的自定义事件
  const changeLevelEmit = async (val: string) => {
    try {
      await PutClientState({
        id: currId.value,
        level: val,
      });
      tableTurnRef.value.loadData();
    } catch (err: unknown) {
      console.log(err);
    }
    levelModalVisible.value = false;
  };

  // 删除一项
  const deleteItem = async (id: number, rowIndex: number) => {
    try {
      await DelClientList({
        id,
      });
      tableTurnRef.value.tableList.splice(rowIndex, 1);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  // 转黑名单
  const changeBlack = async (id: number, rowIndex: number) => {
    try {
      await PutClient2Black({
        id,
      });
      tableTurnRef.value.tableList.splice(rowIndex, 1);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const getDemandDeriveData = () => {
    GetClientDeriveExcel('客户模板');
  };
</script>

<style scoped lang="less">
  .search-box {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    padding: 10px;
    margin-top: -7px;
  }
</style>
